package functional.conception;

import java.util.function.Function;

/**
 * 函数式编程：函数组合
 *
 * @author Liu Yicong
 * @date 2025/10/7
 */
public class FunctionComposition {
	public static void main(String[] args) {
		Function<Integer, Integer> add2 = x -> x + 2;    // add2(x)
		Function<Integer, Integer> times3 = x -> x * 3;  // times3(x)

		// 定义一个新函数pipeline为 y = (x + 2) * 3
		Function<Integer, Integer> pipeline = add2.andThen(times3);

		// 等价：times3.compose(add2) -> times3(add2(x))
		Function<Integer, Integer> pipeline2 = times3.compose(add2);

		System.out.println("pipeline.apply(4) = " + pipeline.apply(4)); // (4+2)*3 = 18
		System.out.println("pipeline2.apply(4) = " + pipeline2.apply(4)); // 同上 18

		// 自己实现一个泛型 compose（f ∘ g）
		Function<Integer, Integer> composed = compose(times3, add2); // times3(add2(x))
		System.out.println("composed.apply(4) = " + composed.apply(4)); // 18
	}

	static <T> Function<T, T> compose(Function<T, T> f, Function<T, T> g) {
		return x -> f.apply(g.apply(x));
	}
}
